package info.sgu.ttdt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.androidhive.slidingmenu.R;
import info.sgu.ttdt.adapter.DatabaseHelper;
import info.sgu.ttdt.adapter.JsonUrl;
import info.sgu.ttdt.model.BookMark;
import info.sgu.ttdt.model.DiemChiTiet;
import info.sgu.ttdt.model.DiemTongQuat;
import info.sgu.ttdt.model.HocKy;
import info.sgu.ttdt.model.TaiKhoan;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class DiemThiFragment extends ListFragment {

	private ProgressDialog pDialog;

	// URL to get contacts JSON
	private static String url;

	// JSON Node names
	private static final String tag_mamonhoc = "mamonhoc";
	private static final String tag_tenmonhoc = "tenmonhoc";
	private static final String tag_sotinchi = "sotinchi";
	private static final String tag_phantramkiemtra = "phantramkiemtra";
	private static final String tag_phantramthi = "phantramthi";
	private static final String tag_diemkiemtra = "diemkiemtra";
	private static final String tag_diemthilanmot = "diemthilanmot";
	private static final String tag_diemtongkethemuoi = "diemtongkethemuoi";
	private static final String tag_diemtongketdiemchu = "diemtongketdiemchu";

	private static final String tag_diemtrungbinhhockyhemuoi = "diemtrungbinhhockyhemuoi";
	private static final String tag_diemtrungbinhhockyhebon = "diemtrungbinhhockyhebon";
	private static final String tag_diemtrungbinhtichluyhemuoi = "diemtrungbinhtichluyhemuoi";
	private static final String tag_diemtrungbinhtichluyhebon = "diemtrungbinhtichluyhebon";
	private static final String tag_sotinchidat = "sotinchidat";
	private static final String tag_sotinchitichluy = "sotinchitichluy";
	private static final String tag_diemtrungbinhrenluyenhocky = "diemtrungbinhrenluyenhocky";
	private static final String tag_phanloaidtbrenluyenhocky = "phanloaidtbrenluyenhocky";

	private static final String tag_tenhocky = "tenhocky";
	
	private static final String tag_masinhvien = "masinhvien";
	private static final String tag_tensinhvien = "tensinhvien";
	private static final String tag_lop = "lop";
	private static final String tag_nganh = "nganh";
	private static final String tag_khoa = "khoa";
	private static final String tag_hedaotao = "hedaotao";
	private static final String tag_khoahoc = "khoahoc";

	Spinner spinner;
	List<String> str;

	DatabaseHelper db;
	List<DiemChiTiet> datalist;
	// contacts JSONArray
	JSONArray data = null;
	ViewSwitcher viewSwitcher;
	String masinhvien;
	// Hashmap for ListView
	ArrayList<HashMap<String, String>> dataList;

	Button bt;
	ImageButton btn_reload;
	ImageButton btn_bookmark;
	EditText txt;;
	TextView tv;
	String name;

	public DiemThiFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_diemthi, container,
				false);
		SharedPreferences settings = getActivity()
				.getSharedPreferences("UserInfo", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("type", 3);
		editor.commit();
		spinner = (Spinner) rootView.findViewById(R.id.spinner);
		viewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher1);
		txt = (EditText) rootView.findViewById(R.id.editText1);
		tv = (TextView) rootView.findViewById(R.id.textView1);
		OnItemSelectedListener SelectedListener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				Load(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner.setOnItemSelectedListener(SelectedListener);
		db = new DatabaseHelper(getActivity());
		datalist = new ArrayList<DiemChiTiet>();
		dataList = new ArrayList<HashMap<String, String>>();
		str = new ArrayList<String>();
		bt = (Button) rootView.findViewById(R.id.button1);
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				masinhvien = txt.getText().toString();
				url = JsonUrl.getUrlDiemThi(masinhvien);
				viewSwitcher.showNext();
				if (db.checkDiem(masinhvien)) {
					if (db.checkTaiKhoan(masinhvien)) {
						TaiKhoan tk = db.getTaiKhoan(masinhvien);
						name = tk.getTensinhvien();
					}
					Load2(0);
				} else {
					// Calling async task to get json
					new GetContacts().execute();
				}
			}
		});
		btn_reload = (ImageButton) rootView.findViewById(R.id.button_reload);
		btn_reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				url = JsonUrl.getUrlDiemThi(masinhvien);
				// Calling async task to get json
				new GetContacts().execute();
			}
		});
		btn_bookmark = (ImageButton) rootView.findViewById(R.id.imageButton1);
		btn_bookmark.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!db.checkBookmark(masinhvien, "Điểm thi"))
				{
					BookMark bm = new BookMark(masinhvien, name, "Điểm thi");
					db.createBookmark(bm);
					Toast.makeText(getActivity(), "Lưu Bookmark thành công", Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(getActivity(), "Bookmark đã tồn tại", Toast.LENGTH_SHORT).show();
			}
		});
		//SharedPreferences settings = getActivity().getSharedPreferences("UserInfo", 0);
		String masv = settings.getString("masinhvien", "").toString();
		if (!masv.equals("null") && !masv.isEmpty()) {
			masinhvien = settings.getString("masinhvien", "").toString();
			name = settings.getString("tensinhvien", "").toString();
			url = JsonUrl.getUrlDiemThi(masinhvien);
			viewSwitcher.showNext();
			if (db.checkDiem(masinhvien)) {
				Load2(0);
			} else {
				// Calling async task to get json
				new GetContacts().execute();
			}
		}

		return rootView;
	}

	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Vui lòng chờ...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			if(!db.checkTaiKhoan(masinhvien))
			{
				String url2 = JsonUrl.getUrlTaiKhoan(masinhvien);
				String jsonStr2 = sh.makeServiceCall(url2, ServiceHandler.GET);
				Log.d("Response: ", "> " + jsonStr2);
	
				if (jsonStr2 != null) {
					try {
						JSONObject jsonObj = new JSONObject(jsonStr2);
						JSONObject c = jsonObj.getJSONObject("taikhoan");
						if (c != null) {
							String masinhvien = c.getString(tag_masinhvien);
							String tensinhvien = c.getString(tag_tensinhvien);
							String lop = c.getString(tag_lop);
							String nganh = c.getString(tag_nganh);
							String khoa = c.getString(tag_khoa);
							String hedaotao = c.getString(tag_hedaotao);
							String khoahoc = c.getString(tag_khoahoc);
	
							TaiKhoan tk = new TaiKhoan(masinhvien, tensinhvien,
									lop, nganh, khoa, hedaotao, khoahoc, "");
							db.createTaiKhoan(tk);
						}
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					Log.e("ServiceHandler", "Couldn't get any data from the url");
				}
			}
			
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					JSONObject c4 = jsonObj.getJSONObject("taikhoan");
					name = c4.getString("tensinhvien");
					// Getting JSON Array node
					JSONArray data2 = jsonObj.getJSONArray("hocky");
					if (data2.length() > 0) {
						db.deleteDiem(masinhvien);
						db.deleteDiemTQ(masinhvien);
						db.deleteHocKy(masinhvien, "diem");
					}
					for (int j = 0; j < data2.length(); j++) {
						JSONObject c2 = data2.getJSONObject(j);
						data = c2.getJSONArray("chitiet");
						// looping through All Contacts
						for (int i = 0; i < data.length(); i++) {
							JSONObject c = data.getJSONObject(i);

							String mamonhoc = c.getString(tag_mamonhoc);
							String tenmonhoc = c.getString(tag_tenmonhoc);
							String sotinchi = c.getString(tag_sotinchi);
							String phantramkiemtra = c
									.getString(tag_phantramkiemtra);
							String phantramthi = c.getString(tag_phantramthi);
							String diemkiemtra = c.getString(tag_diemkiemtra);
							String diemthilanmot = c
									.getString(tag_diemthilanmot);
							String diemtongkethemuoi = c
									.getString(tag_diemtongkethemuoi);
							String diemtongketdiemchu = c
									.getString(tag_diemtongketdiemchu);

							// tmp hashmap for single contact

							DiemChiTiet ct = new DiemChiTiet(mamonhoc,
									tenmonhoc, sotinchi, phantramkiemtra,
									phantramthi, diemkiemtra, diemthilanmot,
									diemtongkethemuoi, diemtongketdiemchu);
							db.createDiemChiTiet(ct, j, masinhvien);

							// adding each child node to HashMap key => value

						}
						String tenhocky = c2.getString(tag_tenhocky);
						HocKy hk = new HocKy(tenhocky);
						db.createHocKy(hk, masinhvien, "diem");

						JSONObject c3 = c2.getJSONObject("tongquat");
						String diemtrungbinhhockyhemuoi = c3
								.getString(tag_diemtrungbinhhockyhemuoi);
						String diemtrungbinhhockyhebon = c3
								.getString(tag_diemtrungbinhhockyhebon);
						String diemtrungbinhtichluyhemuoi = c3
								.getString(tag_diemtrungbinhtichluyhemuoi);
						String diemtrungbinhtichluyhebon = c3
								.getString(tag_diemtrungbinhtichluyhebon);
						String sotinchidat = c3.getString(tag_sotinchidat);
						String sotinchitichluy = c3
								.getString(tag_sotinchitichluy);
						String diemtrungbinhrenluyenhocky = c3
								.getString(tag_diemtrungbinhrenluyenhocky);
						String phanloaidtbrenluyenhocky = c3
								.getString(tag_phanloaidtbrenluyenhocky);

						DiemTongQuat tq = new DiemTongQuat(
								diemtrungbinhhockyhemuoi,
								diemtrungbinhhockyhebon,
								diemtrungbinhtichluyhemuoi,
								diemtrungbinhtichluyhebon, sotinchidat,
								sotinchitichluy, diemtrungbinhrenluyenhocky,
								phanloaidtbrenluyenhocky);
						db.createDiemTongQuat(tq, j, masinhvien);
					}
					datalist = db.getAllDiems(0, masinhvien);
					for (DiemChiTiet c : datalist) {
						HashMap<String, String> data = new HashMap<String, String>();
						data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
						data.put(tag_tenmonhoc,
								"Tên môn học: " + c.getTenmonhoc());
						data.put(tag_sotinchi, "Số tín chỉ: " + c.getSotinchi());
						data.put(tag_phantramkiemtra,
								"% KT: " + c.getPhantramkiemtra());
						data.put(tag_phantramthi,
								"% Thi: " + c.getPhantramthi());
						data.put(tag_diemkiemtra,
								"Điểm KT: " + c.getDiemkiemtra());
						data.put(tag_diemthilanmot,
								"Điểm Thi L1: " + c.getDiemthilanmot());
						data.put(tag_diemtongkethemuoi,
								"TK(10): " + c.getDiemtongkethemuoi());
						data.put(tag_diemtongketdiemchu,
								"TK(CH): " + c.getDiemtongketdiemchu());
						// adding contact to contact list
						dataList.add(data);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			DiemTongQuat tq = db.getDiemTQs(0, masinhvien);
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(
					tag_mamonhoc,
					"Điểm trung bình học kỳ hệ 10/100: "
							+ tq.getDiemtrungbinhhockyhemuoi());
			data.put(
					tag_tenmonhoc,
					"Điểm trung bình học kỳ hệ 4: "
							+ tq.getDiemtrungbinhhockyhebon());
			data.put(
					tag_sotinchi,
					"Điểm trung bình tích lũy: "
							+ tq.getDiemtrungbinhtichluyhemuoi());
			data.put(tag_phantramkiemtra, "Điểm trung bình tích lũy (hệ 4): "
					+ tq.getDiemtrungbinhtichluyhebon());
			data.put(tag_phantramthi, "Số tín chỉ đạt: " + tq.getSotinchidat());
			data.put(tag_diemkiemtra,
					"Số tín chỉ tích lũy: " + tq.getSotinchitichluy());
			data.put(
					tag_diemthilanmot,
					"Điểm Trung Bình Rèn Luyện HK: "
							+ tq.getDiemtrungbinhrenluyenhocky());
			data.put(tag_diemtongkethemuoi,
					"Phân Loại ĐTBRL HK: " + tq.getPhanloaidtbrenluyenhocky());
			// adding contact to contact list
			dataList.add(data);
			List<HocKy> hks = db.getHocKys(masinhvien, "diem");
			for (HocKy hk : hks) {
				str.add(hk.getTenhocky());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
					R.layout.list_item, new String[] { tag_mamonhoc,
							tag_tenmonhoc, tag_sotinchi, tag_phantramkiemtra,
							tag_phantramthi, tag_diemkiemtra,
							tag_diemthilanmot, tag_diemtongkethemuoi,
							tag_diemtongketdiemchu }, new int[] { R.id.text1,
							R.id.text2, R.id.text3, R.id.text4, R.id.text5,
							R.id.text6, R.id.text7, R.id.text8, R.id.text9 });

			setListAdapter(adapter);

			ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item, str);
			spinner.setAdapter(adapter_state);
			tv.setText(masinhvien + " - " + name);
			int num = db.numberTaiKhoan();
			((MainActivity)getActivity()).NumberAccount(num, 3);
		}

	}

	private void Load(int position) {
		dataList.clear();
		datalist = db.getAllDiems(position, masinhvien);
		for (DiemChiTiet c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_sotinchi, "Số tín chỉ: " + c.getSotinchi());
			data.put(tag_phantramkiemtra, "% KT: " + c.getPhantramkiemtra());
			data.put(tag_phantramthi, "% Thi: " + c.getPhantramthi());
			data.put(tag_diemkiemtra, "Điểm KT: " + c.getDiemkiemtra());
			data.put(tag_diemthilanmot, "Điểm Thi L1: " + c.getDiemthilanmot());
			data.put(tag_diemtongkethemuoi,
					"TK(10): " + c.getDiemtongkethemuoi());
			data.put(tag_diemtongketdiemchu,
					"TK(CH): " + c.getDiemtongketdiemchu());
			// adding contact to contact list
			dataList.add(data);
		}
		DiemTongQuat tq = db.getDiemTQs(position, masinhvien);
		HashMap<String, String> data = new HashMap<String, String>();
		data.put(
				tag_mamonhoc,
				"Điểm trung bình học kỳ hệ 10/100: "
						+ tq.getDiemtrungbinhhockyhemuoi());
		data.put(
				tag_tenmonhoc,
				"Điểm trung bình học kỳ hệ 4: "
						+ tq.getDiemtrungbinhhockyhebon());
		data.put(
				tag_sotinchi,
				"Điểm trung bình tích lũy: "
						+ tq.getDiemtrungbinhtichluyhemuoi());
		data.put(
				tag_phantramkiemtra,
				"Điểm trung bình tích lũy (hệ 4): "
						+ tq.getDiemtrungbinhtichluyhebon());
		data.put(tag_phantramthi, "Số tín chỉ đạt: " + tq.getSotinchidat());
		data.put(tag_diemkiemtra,
				"Số tín chỉ tích lũy: " + tq.getSotinchitichluy());
		data.put(
				tag_diemthilanmot,
				"Điểm Trung Bình Rèn Luyện HK: "
						+ tq.getDiemtrungbinhrenluyenhocky());
		data.put(tag_diemtongkethemuoi,
				"Phân Loại ĐTBRL HK: " + tq.getPhanloaidtbrenluyenhocky());
		// adding contact to contact list
		dataList.add(data);
		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item, new String[] { tag_mamonhoc, tag_tenmonhoc,
						tag_sotinchi, tag_phantramkiemtra, tag_phantramthi,
						tag_diemkiemtra, tag_diemthilanmot,
						tag_diemtongkethemuoi, tag_diemtongketdiemchu },
				new int[] { R.id.text1, R.id.text2, R.id.text3, R.id.text4,
						R.id.text5, R.id.text6, R.id.text7, R.id.text8,
						R.id.text9 });

		setListAdapter(adapter);
	}

	private void Load2(int position) {
		dataList.clear();
		datalist = db.getAllDiems(position, masinhvien);
		for (DiemChiTiet c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_sotinchi, "Số tín chỉ: " + c.getSotinchi());
			data.put(tag_phantramkiemtra, "% KT: " + c.getPhantramkiemtra());
			data.put(tag_phantramthi, "% Thi: " + c.getPhantramthi());
			data.put(tag_diemkiemtra, "Điểm KT: " + c.getDiemkiemtra());
			data.put(tag_diemthilanmot, "Điểm Thi L1: " + c.getDiemthilanmot());
			data.put(tag_diemtongkethemuoi,
					"TK(10): " + c.getDiemtongkethemuoi());
			data.put(tag_diemtongketdiemchu,
					"TK(CH): " + c.getDiemtongketdiemchu());
			// adding contact to contact list
			dataList.add(data);
		}
		DiemTongQuat tq = db.getDiemTQs(position, masinhvien);
		HashMap<String, String> data = new HashMap<String, String>();
		data.put(
				tag_mamonhoc,
				"Điểm trung bình học kỳ hệ 10/100: "
						+ tq.getDiemtrungbinhhockyhemuoi());
		data.put(
				tag_tenmonhoc,
				"Điểm trung bình học kỳ hệ 4: "
						+ tq.getDiemtrungbinhhockyhebon());
		data.put(
				tag_sotinchi,
				"Điểm trung bình tích lũy: "
						+ tq.getDiemtrungbinhtichluyhemuoi());
		data.put(
				tag_phantramkiemtra,
				"Điểm trung bình tích lũy (hệ 4): "
						+ tq.getDiemtrungbinhtichluyhebon());
		data.put(tag_phantramthi, "Số tín chỉ đạt: " + tq.getSotinchidat());
		data.put(tag_diemkiemtra,
				"Số tín chỉ tích lũy: " + tq.getSotinchitichluy());
		data.put(
				tag_diemthilanmot,
				"Điểm Trung Bình Rèn Luyện HK: "
						+ tq.getDiemtrungbinhrenluyenhocky());
		data.put(tag_diemtongkethemuoi,
				"Phân Loại ĐTBRL HK: " + tq.getPhanloaidtbrenluyenhocky());
		// adding contact to contact list
		dataList.add(data);
		List<HocKy> hks = db.getHocKys(masinhvien, "diem");
		for (HocKy hk : hks) {
			str.add(hk.getTenhocky());
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item, new String[] { tag_mamonhoc, tag_tenmonhoc,
						tag_sotinchi, tag_phantramkiemtra, tag_phantramthi,
						tag_diemkiemtra, tag_diemthilanmot,
						tag_diemtongkethemuoi, tag_diemtongketdiemchu },
				new int[] { R.id.text1, R.id.text2, R.id.text3, R.id.text4,
						R.id.text5, R.id.text6, R.id.text7, R.id.text8,
						R.id.text9 });

		setListAdapter(adapter);

		ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, str);
		spinner.setAdapter(adapter_state);
		tv.setText(masinhvien + " - " + name);
	}

}
